package file;



/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 25397
 * Date: 2022-04-12
 * Time: 14:35
 */
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Scanner;
public class Demo14 {
    private static boolean containsWord(File f, String word) {//判断文件内容是否包含word
        StringBuilder stringBuilder=new StringBuilder();
        //把f中的内容都读出来，放到一个StringBuilder中
        try(Reader reader=new FileReader(f)){
            char[] buffer=new char[1024];
            while(true){
                int len=reader.read(buffer);
                if(len==-1){
                    break;
                }
                //把这段读到的结果，放到StringBuilder中
                stringBuilder.append(buffer,0,len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return stringBuilder.indexOf(word)!=-1;
        //indexOf返回的是字符串下标，如果word在stringBuilder中不存在，返回-1
    }
    private static void scanDir(File rootDir,String word) throws IOException {
        //1.先列出rootDir中有哪些内容
        File[] files=rootDir.listFiles();
        if(files==null){
            return;
        }

        //2.遍历每个元素，针对普通文件和目录分别进行处理
        for(File f:files){
            if(f.isFile()){
                //文件进行内容查找
                if(containsWord(f,word)){
                    System.out.println(f.getCanonicalPath());
                }
            }else{
                //目录就继续往下递归
                scanDir(f,word);
            }
        }
    }



    public static void main(String[] args) throws IOException {
        //1.输入要扫描的文件路径
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入要扫描的路径");
        String rootDirPath=scanner.next();
        System.out.println("请输入要查找的关键词");
        String word=scanner.next();
        File rootDir=new File(rootDirPath);
        if(!rootDir.isDirectory()){
            System.out.println("输入的路径非法");
            return;
        }
        //2.递归的进行遍历
        scanDir(rootDir,word);
    }

}
